var express = require('express');
var router = express.Router();
var mongoose = require('mongoose');

var Goods = require("../models/goods");

//连接数据库
// 账号密码
// mongoose.connect("mongodb://root:1345@localhost/dumall",{ useNewUrlParser: true });

mongoose.connect("mongodb://localhost/dumall", {useNewUrlParser: true});

//连接成功
mongoose.connection.on('connected', function () {
  console.log('success')
})
//连接失败
mongoose.connection.on('error', function () {
  console.log('fail')
})
//连接中断
mongoose.connection.on('disconnected', function () {
  console.log('disconnected')
})

//查询商品列表
router.get('/list', function (req, res, next) {
  let page = parseInt(req.param('page'));
  let pageSize = parseInt(req.param('pageSize'));
  let priceLevel = req.param('priceLevel');
  let sort = req.param('sort');
  let skip = (page - 1) * pageSize;//跳过几条
  var priceGt = '', priceLte = '';
  let params = {};
  if (priceLevel != 'all') {
    switch (priceLevel) {
      case '0':
        priceGt = 0;
        priceLte = 100;
        break;
      case '1':
        priceGt = 100;
        priceLte = 500;
        break;
      case '2':
        priceGt = 500;
        priceLte = 1000;
        break;
      case '3':
        priceGt = 1000;
        priceLte = 2000;
        break;
    }
     params = {
         salePrice: {
           $gt:priceGt,
           $lte:priceLte
         }
     };
  }

  let goodsModel = Goods.find(params).skip(skip).limit(pageSize);
  goodsModel.sort({'salePrice': sort});//排序
  goodsModel.exec(function (err, doc) {
    if (err) {
      res.json({
        status: '1',
        msg: err.message
      })
    } else {
      res.json({
        status: '0',
        msg: '',
        result: {
          count: doc.length,
          list: doc
        }
      })
    }
  })
})
//加入购物车
router.post("/addCart",function (req,res,next) {
  var userId = '100011',productId = req.body.productId;
  var User = require("../models/user");
  User.findOne({userId:userId},function (err1,userDoc) {
    if(err1){
      res.json({
        status:"1",
        msg:err1.message
      })
    }else {
      if(userDoc){
        let goodsItem = '';
        userDoc.cartList.forEach(function (item) {
             if(item.productId==productId){
               goodsItem = item;
               item.productNum ++;
             }
        });
        if(goodsItem){
          userDoc.save(function (err3,doc2) {
            if(err3){
              res.json({
                status:"1",
                msg:err3.message
              })
            }else {
              res.json({
                status:"0",
                msg:'',
                result:'success'
              })
            }
          })
        }else {
          Goods.findOne({productId:productId},function (err2,doc) {
            if(err2){
              res.json({
                status:"1",
                msg:err2.message
              })
            }else {
              if(doc){
                doc.productNum = 1;
                doc.checked = 1;
                userDoc.cartList.push(doc);
                userDoc.save(function (err3,doc2) {
                  if(err3){
                    res.json({
                      status:"1",
                      msg:err3.message
                    })
                  }else {
                    res.json({
                      status:"0",
                      msg:'',
                      result:'success'
                    })
                  }
                })
              }
            }
          })

        }
      }
    }
  })
})
module.exports = router;
